package com.wsc.it.techfuser;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.wsc.it.bridge.vo.ShopOrderGoodsOSM;
import com.wsc.it.bridge.vo.ShopOrderNum;
import com.wsc.it.bridge.vo.ShopOrderOSM;
import com.wsc.it.techfuser.vo.OrderDetail;
import com.wsc.it.techfuser.vo.OrderPayment;
import com.wsc.it.techfuser.vo.Receiver;
import com.wsc.it.techfuser.vo.TechfuserOrderRequest;
import com.wsc.it.techfuser.vo.TechfuserRequestBase;
import com.wsc.it.utils.MD5Utils;
import com.wsc.it.utils.PrinterUtil;

/**
 * 请求方法
 * @author wsc58888
 *
 */
public class TechfuserUtil {
	private static final Logger log = LoggerFactory.getLogger(PrinterUtil.class);

	public static String listToString(List<String> list) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			if (i == list.size() - 1) {
				sb.append(list.get(i));
			} else {
				sb.append(list.get(i));
				sb.append(",");
			}
		}
		return sb.toString();
	}

	public static String TechfuserHttpPost(String postUrl, Object data, String appid, String secret) {

		TechfuserRequestBase<Object> reposeBase = new TechfuserRequestBase<>();
		reposeBase.setData(data);
		long time = new Date().getTime();
		reposeBase.setTimestamp("" + time);
		reposeBase.setQid("techfuser-" + time);
		reposeBase.setVersion("2.3");
		String json = "appid=" + appid + "&" + "data=" + JSON.toJSONString(data) + "&" + "qid=" + reposeBase.getQid()
				+ "&" + "timestamp=" + reposeBase.getTimestamp() + "&" + "version=" + reposeBase.getVersion() + "&"
				+ secret;
		reposeBase.setSign(MD5Utils.md5With32(json));
		String requstJson = JSON.toJSONString(reposeBase);
		HttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(postUrl);
		post.addHeader("Content-type", "application/json; charset=utf-8");
		post.setHeader("Accept", "application/json");
		post.setEntity(new StringEntity(requstJson, StandardCharsets.UTF_8));
		post.setHeader("appid", appid);
		for (int retryTime = 0; retryTime < 5; retryTime++) {
			try {
				HttpResponse httpResponse = client.execute(post);
				HttpEntity entity = httpResponse.getEntity();
				String responseJson = EntityUtils.toString(entity);
				log.info("牵牛花接口: {}  request: {} \r\n response: {}", postUrl, requstJson, responseJson);
				return responseJson;
			} catch (Exception e) {
				log.error("调用牵牛花接口: {} 异常: {}", postUrl, e.getMessage());
			} finally {
				log.info("第{}次,调用牵牛花接口:{}", retryTime + 1, postUrl);
			}
		}
		return null;
	}

	/**
	 * { "data": { "pay_over": true, "channel_sheetno": "1802091103245945",
	 * "receiver": { "address": "北京中南海", "gender": "1", "mobile": "130XXXXXXXX",
	 * "name": "帅哥哥哥" }, "buyer": { "tel": "137XXXXXXXX", "note": "这是下单人的备注",
	 * "email": "101456@qq.com", "account": "qnh-test", "card_code": "sjdhjaskd",
	 * "nick": "昵称", "address": "湖北武汉街道口理工大" }, "pacakge_fee": 0, "lunchbox_fee": 0,
	 * "weight": 255, "commission_value": 0.3, "total_disc_value": 1,
	 * "total_sj_disc": 0.2, "total_pt_disc": 0.8, "total_sj_dp": 0.7,
	 * "total_pt_dp": 0.3, "payable_value": 4.5, "order_time": "2018-11-01
	 * 15:04:34", "order_details": [{ "item_code": "12329", "original_price": 6.5,
	 * "money": 5.5, "qty": 1, "pos_qty": 0, "electronic_goods": false,
	 * "coefficient": 1.0, "disc_value": 0.5, "disc_value_pt": 0.5, "disc_bt_sj":
	 * 0.7, "disc_bt": 0.3, "weight": 255, "activity_id": "", "supplier_rate": 0.5,
	 * "commission_value": 0.3, "name": "可口可乐2.3L", "barcode": "6928804011258",
	 * "sale_price": 5.5 }], "total_sale_value": 5.3, "billtype": "1",
	 * "order_payments": [{ "name": "商城系统支付", "payment": 4.5, "keyword": "1000" }],
	 * "invoice": { "type": "0", "title": "个人", "duty_no": "111111111", "content":
	 * "", "money": "4.5" }, "logistics_mode_keyword": "0", "selfPickCode": "123",
	 * "pickup_org_code":"123", "total_item_value": 5.5, "org_name": "XXXX店",
	 * "channel_keyword": "APP", "org_code": "0108", "payable_logistics_value": 0 },
	 *
	 * "timestamp": "1389751221", "sign": "00934d00d0aea6f12161edfb6456143d", "qid":
	 * "e58cf0a2-4f02-4d23-a2c8-c80c479ab08", "version": "2.3" }
	 * 
	 * @param shopOrderOSM
	 * @param bilitype
	 * @return
	 */
	public static TechfuserOrderRequest orderSwitchTechfuserOrder(ShopOrderOSM shopOrderOSM, String bilitype) {
		BigDecimal actualPay = shopOrderOSM.getActualPay();// 实付金额
		BigDecimal deliveryFee = new BigDecimal("0.00");// 惠购券减免金额
		BigDecimal packingFee = new BigDecimal("0.00");// 配送费
		BigDecimal hgoCouponReduce = new BigDecimal("0.00");// 打包费
		BigDecimal reductionAmount = new BigDecimal("0.00");// 满减
		if (shopOrderOSM.getHgoCouponReduce() != null) {
			hgoCouponReduce = shopOrderOSM.getHgoCouponReduce();// 惠购券减免金额
		}
		if (shopOrderOSM.getDeliveryFee() != null) {
			deliveryFee = shopOrderOSM.getDeliveryFee();// 配送费
		}
		if (shopOrderOSM.getPackingFee() != null) {
			packingFee = shopOrderOSM.getPackingFee();// 打包费
		}
		if (shopOrderOSM.getReductionAmount() != null) {
			reductionAmount = shopOrderOSM.getReductionAmount(); // 满减
		}
		// 牵牛花收入金额（订单总额）
		BigDecimal totalSaleValue = actualPay.add(hgoCouponReduce).subtract(deliveryFee).subtract(packingFee);

		BigDecimal prices = new BigDecimal(0.00); // 商品总价

		TechfuserOrderRequest order = new TechfuserOrderRequest();
		order.setChannel_sheetno(shopOrderOSM.getOrderNumber()); // 订单号
		order.setChannel_keyword("LRG"); // 渠道简称
		order.setPay_over(true); // 值为true表示已经付款；值为false表示货到付款
		order.setBilltype(bilitype); // 单据类型1: 订单；2:退单；7:礼金卡订单
		if ("1".equals(bilitype)) {
			order.setStatus("11"); // 11已完成订单、5退单
		} else if ("2".equals(bilitype)) {
			order.setReturn_order_sn(shopOrderOSM.getOrderNumber());// 退单号 单据类型为2 传订单号
			order.setStatus("5"); // 11已完成订单、5退单
		}
		order.setTotal_sale_value(totalSaleValue.doubleValue());// 收入金额（订单总额）
		order.setTotal_disc_value(reductionAmount.doubleValue());// 订单总优惠额 = (商家订单总优惠+平台订单总优惠)
		order.setTotal_sj_disc(reductionAmount.doubleValue()); // 商家订单总优惠
		order.setTotal_pt_disc(0.0); // 平台订单总优惠
		order.setTotal_sj_dp(0.0); // 商家单品总优惠
		order.setTotal_pt_dp(0.0); // 平台单品总优惠
		order.setCommission_value(0.0); // 订单收取佣金
		order.setPayable_value(totalSaleValue.doubleValue());// 付款金额

		// 商品信息
		List<ShopOrderGoodsOSM> list = shopOrderOSM.getList();
		List<OrderDetail> orderDetails = new ArrayList<>();

		for (ShopOrderGoodsOSM shopOrderGoodsOSM : list) {
			ShopOrderNum shopOrderNum = shopOrderGoodsOSM.getShopOrderNums().get(0);
			OrderDetail orderDetail = new OrderDetail();
			// 商品售价金额*数量
			BigDecimal money = shopOrderNum.getPrice()
					.multiply(new BigDecimal(shopOrderNum.getPurchaseQuantity().toString()));
			orderDetail.setItem_code(shopOrderGoodsOSM.getGoodsCode()); // 商品ERP编码
			orderDetail.setBarcode(shopOrderGoodsOSM.getGoodsBarcode()); // 商品条码
			orderDetail.setName(shopOrderGoodsOSM.getGoodsName()); // 商品名称
			orderDetail.setOriginal_price(shopOrderNum.getPrice().doubleValue()); // 商品原价
			if (shopOrderGoodsOSM.getGoodsWeight() != null) {
				orderDetail.setWeight(shopOrderGoodsOSM.getGoodsWeight().intValue()); // 单个商品重量 克
			} else {
				orderDetail.setWeight(100);
			}

			orderDetail.setSale_price(shopOrderNum.getPrice().doubleValue()); // 商品售价
			orderDetail.setQty(shopOrderNum.getPurchaseQuantity()); // 数量
			orderDetail.setMoney(money.doubleValue()); // 商品售价金额= 商品售价（sale_price)* 数量（qty）
			prices = prices.add(money); // 计算总价
			orderDetails.add(orderDetail);
		}
		// 满减 除 总价
		BigDecimal unitPrice = reductionAmount.divide(prices, 2, BigDecimal.ROUND_DOWN); // 取小数点后2位
		BigDecimal remainder = reductionAmount; // 记录余数
		for (int i = 0; i < list.size(); i++) {
			BigDecimal disc = unitPrice
					.multiply(list.get(i).getShopOrderNums().get(0).getPrice().setScale(0, BigDecimal.ROUND_DOWN)); // 计算单品优惠并且保留2位小数
			remainder = remainder.subtract(disc); // 记录余数算法
			orderDetails.get(i).setDisc_value(disc.doubleValue()); // 单品优惠
		}

		if (remainder.doubleValue() > 0) { // 判断是否还有余数
			BigDecimal compareToRemainder = new BigDecimal("100.00"); // 记录余数分配之后除不尽剩下的余数
			BigDecimal compareToDisc = new BigDecimal("0.00"); // 记录除不尽可以分配的余数
			int getint = 0; // 记录集合插入坐标
			boolean isCompareTo = true; // 余数分配不尽标记
			for (int i = 0; i < list.size(); i++) {
				if (orderDetails.get(i).getQty() == 1) { // 数量为1 直接分配余数
					Double disc_value = orderDetails.get(i).getDisc_value();
					BigDecimal disc = remainder.add(new BigDecimal(disc_value.toString()));
					orderDetails.get(i).setDisc_value(disc.doubleValue());
					isCompareTo = false;
					break;
				} else {
					BigDecimal disc = remainder.divide(new BigDecimal(orderDetails.get(i).getQty().toString()), 2,
							BigDecimal.ROUND_DOWN); // 余数除数量 保留2位
					BigDecimal remainder2 = disc.multiply(new BigDecimal(orderDetails.get(i).getQty().toString())); // 反算
					disc = disc.add(new BigDecimal(orderDetails.get(i).getDisc_value().toString())); // 计算余数分配
					if (remainder.compareTo(remainder2) == 0) { // 判断 反算的结果 是否为0;反之除不尽
						orderDetails.get(i).setDisc_value(disc.doubleValue());
						isCompareTo = false;
						break;
					} else {
						BigDecimal subtract = remainder.subtract(remainder2); // 反算出除不尽剩下的余数
						if (subtract.compareTo(compareToRemainder) <= 0) { // 走完for循环 取反算出除不尽剩下的余数 最小的那个
							compareToRemainder = subtract; // 记录余数分配之后除不尽剩下的余数
							getint = i; // 记录集合插入坐标
							compareToDisc = disc; // 记录除不尽可以分配的余数
						}
					}
				}
			}
			if (isCompareTo) { // 余数分配不尽标记
				orderDetails.get(getint).setDisc_value(compareToDisc.doubleValue());
				BigDecimal reductionAmount2 = reductionAmount.subtract(compareToRemainder); // 将无法分配的余数 从优惠去除 （0.01）
				order.setTotal_disc_value(reductionAmount2.doubleValue()); // 订单总优惠额
				order.setTotal_sj_disc(reductionAmount2.doubleValue()); // 商家订单总优惠
			}

		}
		order.setOrder_details(orderDetails);
		order.setTotal_item_value(prices.doubleValue()); // 商品售价总金额
		order.setPayable_logistics_value(0.0); // 配送费
		order.setLogistics_mode_keyword("2");// 订单配送方式0 配送，1 自提，2 商家自送；
		order.setPackage_fee(0.0);
		order.setWeight(shopOrderOSM.getWeight().intValue()); // 订单总重量
		order.setOrg_code("1001"); // 门店编码
		order.setOrg_name(shopOrderOSM.getStoreName()); // 门店名称
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		order.setOrder_time(formatter.format(shopOrderOSM.getCreateTime())); // 下单时间
		order.setGroup_id(0); // 订单类型
		Receiver receiver = new Receiver();
		receiver.setName("wsc58888"); // 收件人姓名
//        receiver.setGender("1");    //收件人性别 1：男 2：女
		receiver.setMobile("13800138000"); // 收件人手机
		receiver.setAddress("广东"); // 收件人地址
		order.setReceiver(receiver);
		List<OrderPayment> orderPayments = new ArrayList<>();
		OrderPayment orderPayment = new OrderPayment();
		orderPayment.setKeyword("10002"); // 支付方式编码
											// （10001：支付宝；10002：微信；10003：银联；10004：钱包；10008：储值卡；10009：积分；10010：劵；99999：其他）
		orderPayment.setName("微信支付"); // 支付方式名称（默认：商城系统支付）
		orderPayment.setPayment(totalSaleValue.doubleValue()); // 支付金额
		orderPayments.add(orderPayment);
		order.setOrder_payments(orderPayments);
		return order;
	}
}
